import axios from 'axios'
import { redirectToLogin } from '@/helpers/local'

// 创建axios实例
const service = axios.create({})

// request拦截器
service.interceptors.request.use(
  config => {
    // 设置请求头
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code !== 200) {
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  }, error => {
    if (error.response && error.response.status === 401) {
      redirectToLogin()
    }
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
